package com.atguigu.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.feign.OrderFeign;
import com.atguigu.domain.Order;
import com.atguigu.domain.Product;
import com.atguigu.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private OrderFeign orderFeign;

    //@SentinelResource 将这个方法设置为sentinel资源
    @SentinelResource(value = "getOrderById",blockHandler = "getOrderByIdBlockHandler")
    @Override
    public Order getOrderById(int id) {
        Order order=new Order();
        order.setId(String.valueOf(id));
        order.setTotalAmount(new BigDecimal("111"));
        order.setUserId("12312");
        order.setNickName("手机");
        order.setAddress("北京故宫");
        order.setProductList(getProductListByFeign());
        return order;
    }

    public Order getOrderByIdBlockHandler(int id, BlockException e) {
        Order order=new Order();

        order.setId(String.valueOf(id));
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId("");
        order.setNickName("暂无数据，原因"+e.toString());
        order.setAddress("");


        return order;
    }

    public List<Product> getProductList(){
        List<Product> productList=new ArrayList<>();
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
//        String url = String.format("http://%s:%d/api/product/%s", host, port,"444");
        String url = String.format("http://service-product/api/product/%s","444");
        log.info("url:{}",url);
        //发送请求
        Product forObject = restTemplate.getForObject(url, Product.class);
        productList.add(forObject);
        return productList;
    }

    public List<Product> getProductListByFeign(){
        List<Product> productList=new ArrayList<>();
        Product model = orderFeign.getProductById("121212");
        productList.add(model);
        return productList;
    }
}
